import { ref } from 'vue'
import { useField } from '@formily/vue'
import { isVoidField } from '@formily/core'

export function useMethods(props: {
  value?: any
  visible?: boolean | string
}, methods?: Record<string, (...args: any[]) => any>) {
  const innerVisible = ref<boolean>(!!props.visible || true)

  const field = useField()
  const getValue = () => {
    return !isVoidField(field.value) ? field.value?.value : null
  }

  const setValue = (val: any) => {
    if (!isVoidField(field.value)) {
      field.value.setValue(val)
    }
  }

  const clearValue = () => {
    // TODO 需要根据不同字段设置不同的值
    setValue(null)
  }

  const show = () => {
    field.value.visible = true
  }

  const hide = () => {
    field.value.visible = false
  }

  const res: Record<string, any> = {
    getValue,
    setValue,
    clearValue,
    show,
    hide,
    innerVisible,
    ...methods,
  }

  for (const k in res) {
    const fieldInstance = field.value as any
    if (k !== 'setValue' && fieldInstance) {
      fieldInstance[k] = res[k] 
    }
  }

  return res
}
